package com.dtflys.easyel.ast;

import com.dtflys.easyel.runtime.EasyElRuntimeContext;

/**
 * @author gongjun[jun.gong@thebeastshop.com]
 * @since v1.0.0
 */
public class ASTTernaryExpression extends ASTExpression {

    private final ASTExpression condition;

    private final ASTExpression trueExpression;

    private final ASTExpression falseExpression;

    public ASTTernaryExpression(ASTExpression condition, ASTExpression trueExpression, ASTExpression falseExpression) {
        super(ASTType.BOOLEAN);
        this.condition = condition;
        this.trueExpression = trueExpression;
        this.falseExpression = falseExpression;
    }

    @Override
    public String getText() {
        StringBuilder builder = new StringBuilder();
        builder.append(condition);
        if (trueExpression != null) {
            builder.append(" ? ");
            builder.append(trueExpression);
            if (falseExpression != null) {
                builder.append(" : ");
                builder.append(falseExpression);
            }
        } else {
            builder.append(" ?: ");
            builder.append(falseExpression);
        }
        return builder.toString();
    }

    @Override
    public String toString() {
        return getText();
    }

    @Override
    public String visit(EasyElRuntimeContext context, ASTVisitor visitor) {
        visitor.visitTernaryExpression(context, this);
        return null;
    }

    public ASTExpression getCondition() {
        return condition;
    }

    public ASTExpression getTrueExpression() {
        return trueExpression;
    }

    public ASTExpression getFalseExpression() {
        return falseExpression;
    }
}
